<template>
  <div class="app">
    <div class="search">
     <span>
       时间：<el-date-picker
         v-model="sateValue"
         type="daterange"
         range-separator="至"
         clearable
         size="small"
         @change="selectTime"
         style="width: 300px"
         start-placeholder="开始日期"
         end-placeholder="结束日期"
     >
      </el-date-picker>
     </span>
      <span>
        姓名：<el-input size="small" style="width: 200px" v-model="commissionName" placeholder="请输入姓名"
                     clearable></el-input>
      </span>
      <span>
        店铺名称：<el-input size="small" style="width: 200px" v-model="storeName" placeholder="请输入店铺名称"
                       clearable></el-input>
      </span>
      <el-button size="small" type="primary" style="margin-left: 10px" @click="search">搜索</el-button>
    </div>
    <div class="topAdd">
      <el-button type="primary" style="float: right;margin-bottom: 5px;margin-left: 15px" @click="downMaterialFee"><i
          class="el-icon-download"></i>下载装卸提成
      </el-button>
      <el-button type="primary" style="float: right;margin-bottom: 5px" @click="addMaterialFee">新增装卸订单</el-button>
      <el-table :data="feeData" border
                :span-method="objectSpanMethod"
                height="calc(100vh - 350px)"
                :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
                :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }">
        <el-table-column prop="commissionName" label="人员"></el-table-column>
        <el-table-column prop="storeName" label="店铺名称"></el-table-column>
        <el-table-column prop="areaName" label="所属仓库"></el-table-column>
        <el-table-column prop="createTime" label="时间"></el-table-column>
        <el-table-column prop="car_material_fee" label="单次提成"></el-table-column>
        <!--        <el-table-column label="总提成">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span style="color: orangered">{{ (scope.row.totalCommissionFee).toFixed(2) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.isCancelCommission==1" style="color: #e57373">已取消提成</span>
            <span v-else>正常</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link @click="cancelFee(scope.row)" style="text-decoration:underline;color: #66b1ff" v-if="scope.row.isCancelCommission!=1">取消提成</el-link>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination style="padding: 20px 0;" align="right" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :current-page="currentPage"
                     :page-sizes="[20, 30, 40, 50]"
                     layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
      </el-pagination>
    </div>
    <el-dialog :visible.sync="addDialog" width="30%" title="添加装卸提成" center>
      <div><span>店铺名称：</span>
        <el-select filterable remote :remote-method="remoteMethod" value-key="orderId"
                   clearable v-model="storeName" size='small' allow-create
                   style="width:300px" placeholder="请输入店铺名称">
          <el-option v-for="item in saleNameList" :key="item.orderId" :label="item.storeName" :value="item.storeName">
          </el-option>
        </el-select>
      </div>
      <div style="margin-top: 20px"><span>装卸人员：</span>
        <el-select v-model="cl" multiple filterable style="width:300px" size="small">
          <el-option
              v-for="(item, i) in list"
              :label="item.userName"
              :value="item.userName"
              :key="i">
          </el-option>
        </el-select>
      </div>
      <div style="margin-top: 20px"><span>货车型号：</span>
        <el-select v-model="carType" style="width:300px" size="small">
          <el-option
              v-for="(item, i) in listCar"
              :label="item.name"
              :value="item.id"
              :key="i">
          </el-option>
        </el-select>
      </div>
      <div style="margin-top: 20px"><span>所属仓库：</span>
        <el-select v-model="areaId" clearable placeholder="请按区域搜索" size="small" style="width: 300px">
          <el-option v-for="item in areaData" :key="item.area" :label="item.areaName" :value="item.area">
          </el-option>
        </el-select>
      </div>
      <div style="margin-top: 20px"><span>提成备注：</span>
        <el-input type="textarea" size="small" style="width: 300px" v-model="remark"></el-input>
      </div>
      <span slot="footer"> <el-button size="small" @click="addDialog=false">取消</el-button>

      <el-button size="small" type="primary" @click="comfirm" v-prevent-re-click>确认</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="cancelDialog" width="30%" title="取消提成" center>
      <div style="margin-top: 20px"><span>取消原因：</span>
        <el-input type="textarea" size="small" style="width: 300px" v-model="reason"></el-input>
      </div>
      <span slot="footer"> <el-button size="small" @click="addDialog=false">取消</el-button>

      <el-button size="small" type="primary" @click="comfirmCancel">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from "xlsx-js-style";
import dayjs from "dayjs";

export default {
  name: "materialFee",
  data() {
    return {
      feeData: [],
      saleNameList: [],
      addDialog: false,
      sateValue: "",
      areaId: "",
      cancelDialog: false,
      storeName: "",
      commissionName: "",
      remark: "",
      carType: "",
      pageNumber:1,
      currentPage:1,
      pageSize:20,
      totalCount: 0,
      reason: "",
      list: [],
      areaData: [],
      params: {},
      cl: [],
      listCar:[{
        name:'60',
        id:1
      },{
        name:'120',
        id:2
      },{
        name:'200',
        id:3
      },{
        name:'300',
        id:4
      },{
        name:'400',
        id:5
      },]
    }
  },
  created() {
    this.getData()
    this.areaList()
    this.$api.orderSelectInstallationUser({loginType: 4})
        .then(res => {
          this.list = res
        })
  },
  methods: {
    areaList() {
      this.$api.areaLedgerAreaList().then(res => {
        this.areaData = res
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.pageNumber = val
      this.getData()
    },
    selectTime(val) {
      if (val) {
        this.params.startTime = dayjs(val[0]).format("YYYY-MM-DD");
        this.params.endTime = dayjs(val[1]).format("YYYY-MM-DD");
      } else {
        this.params.startTime = ''
        this.params.endTime = ''
      }
    },
    getData() {
      const data = {
        ...this.params,
        commissionName: this.commissionName,
        pageNumber:this.pageNumber,
        storeName:this.storeName,
        pageSize:this.pageSize
      }
      this.$api.orderGetCarMaterialCommissionNameList(data).then(res => {
        this.feeData = res.data
        this.totalCount=res.total
      })
    },
    search() {
      const data = {
        ...this.params,
        commissionName: this.commissionName,
        pageNumber:this.pageNumber,
        storeName:this.storeName,
        pageSize:this.pageSize
      }
      this.$api.orderGetCarMaterialCommissionNameList(data).then(res => {
        this.feeData = res.data
        this.totalCount=res.total
      })
    },
    addMaterialFee() {
      this.addDialog = true
      this.storeName = ""
      this.cl = []
      this.remark = ""
      this.areaId = ""
    },
    remoteMethod(val) {
      if (val) {
        const params = {
          storeName: val,
        }
        this.$api.orderGetOrderInfoLikeName(params).then(res => {
          this.saleNameList = res
        })
      }
    },
    comfirm() {
      const newArr = [];
      this.cl.forEach(commissionName => {
        newArr.push({commissionName, storeName: this.storeName, remark: this.remark,areaId:this.areaId,carType:this.carType});
      });
      this.$api.orderAddCarMaterialCommissionName(newArr).then(res => {
        if (res == 1) {
          this.$message.success("添加成功！")
          this.addDialog = false
          this.getData()
        }
      })
    },
    cancelFee(row) {
      this.cancelId = row.id
      this.cancelDialog = true
      this.reason = ""
    },
    comfirmCancel() {
      const data = {
        id: this.cancelId,
        cancelReason: this.reason
      }
      this.$api.orderCancelCarMaterialCommission(data).then(res => {
        if (res == 1) {
          this.$message.success("取消成功！")
          this.cancelDialog = false
          this.getData()
        }
      })
    },

    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      let spanOneArr = [];
      let concatOne = 0;
      this.feeData.map((item, index) => {
        if (index === 0) {
          spanOneArr.push(1);
        } else {
          //合并第一列 installers
          if (item.commissionName === this.feeData[index - 1].commissionName) {
            spanOneArr[concatOne] += 1;
            spanOneArr.push(0);
          } else {
            spanOneArr.push(1);
            concatOne = index;
          }
          ;
        }
      });
      //合并第一列和第二列
      if (columnIndex === 0) {
        const _row = spanOneArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    async downMaterialFee() {
      const resData=await this.$api.orderGetCarMaterialCommissionNameList({pageSize:10000,pageNumber:1}).then()
      const wb = XLSX.utils.book_new();
      let data = [
        ["货车装卸提成表"],
        ['人员姓名',"店铺","所属仓库",'单次提成']
      ];

      resData.data.map(el => {
        data.push([el.commissionName, el.storeName,el.areaName, el.car_material_fee])
      })
      // data[data.length + 1] = [info.storeName,`实付:${info.totalDisCount}`,`补贴:${info.totalDiffPrice}`,`总价:${info.totalAmount}`];
      const ws = XLSX.utils.aoa_to_sheet(data);
      ws['!cols'] = [
        {wpx: 100}, // 第一列宽度为100单位
        {wpx: 150},
        {wpx: 100},
      ];
      ws["A1"].s = {
        alignment: {horizontal: 'center'},
        font: {blod: true, color: {rgb: '000000'}},
        fill: {fgColor: {rgb: 'ff6a00'}}
      }
      ws["A1"].hpt = 140;
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      ws['!merges'] = [
        {s: {r: 0, c: 0}, e: {r: 0, c: 3}},
      ]
      const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'});
      // 创建一个 Blob 对象
      const blob = new Blob([s2ab(wbout)], {type: 'application/octet-stream'});
      // 使用 Blob 对象创建一个链接
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `材料总提成表.xlsx`;

      // 触发下载
      link.click();

      // 清理
      URL.revokeObjectURL(link.href);

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }
    }


  }
}
</script>

<style scoped>

</style>